package cn.calm.xhtml.contentassist.autocomplete;

import java.util.Set;

import javax.xml.namespace.QName;
import static cn.calm.xhtml.XhtmlActivator.logInfo;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.contentassist.ContextInformation;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.ICompletionProposalExtension;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;

import cn.calm.xhtml.entity.Attr;
import cn.calm.xhtml.entity.Tag;

public class ElementProcessorCompletionProposal implements ICompletionProposal,
		ICompletionProposalExtension {
	private String display;
	private Tag tag;
	private QName name;
	private String insertString;
	private int length = -1;
	private Point point;
	private String pattern;

	public ElementProcessorCompletionProposal(Tag t, QName name, String pattern) {
		this.tag = t;
		this.name = name;
		this.pattern = pattern;
		display = this.name.getPrefix() + ":" + tag.getName();
		StringBuffer app = new StringBuffer(getDisplayString());

		Set<Attr> attrs = tag.getAttrs();

		if (attrs != null) {
			for (Attr a : attrs) {
				if (a.isRequired()) {
					app.append(" ");
					app.append(a.getName());
					app.append("=\"\"");
					if (length == -1) {
						length = app.length() - pattern.length() - 2;
					}
				}
			}
		}
		if(t.isHasContent()){
			app.append("></");
			app.append(getDisplayString());
			app.append(">");
		}else{
			app.append("/>");
		}
		
		app.delete(0, pattern.length());
		insertString = app.toString();
		if (length == -1) {
			length = app.length();
		}
	}

	@Override
	public void apply(IDocument arg0) {
		logInfo(arg0.get());
	}

	@Override
	public String getAdditionalProposalInfo() {
		return tag.getDesc();
	}

	@Override
	public IContextInformation getContextInformation() {
		logInfo("getContextInformation");
		return new ContextInformation("Context string", "Information string");
	}

	@Override
	public String getDisplayString() {
		return display;
	}

	@Override
	public Image getImage() {
		return null;
	}

	@Override
	public Point getSelection(IDocument arg0) {
		return point;
	}

	@Override
	public void apply(IDocument arg0, char arg1, int arg2) {
		String string = arg0.get();
		StringBuffer str = new StringBuffer(string);
		int loca = 0;
		if(pattern.equals("")){
			str.insert(arg2, "<");
			loca += 1;
		}
		str.insert(arg2 + loca, insertString);
		point = new Point(arg2 + loca + length + 1, 0);
		arg0.set(str.toString());
	}

	@Override
	public int getContextInformationPosition() {
		logInfo("getContextInformationPosition");
		return 0;
	}

	@Override
	public char[] getTriggerCharacters() {
		return null;
	}

	@Override
	public boolean isValidFor(IDocument arg0, int arg1) {
		logInfo("isValidFor");
		return false;
	}

}
